import { ref } from 'vue'

export const useLockFn = (fn, delay) => {
    const lock = ref(false)

    const closeLock = () => {
        if (typeof delay === 'number') {
            setTimeout(() => {
                lock.value = false
            }, delay)
        } else {
            lock.value = false
        }
    }

    const _fn = async (...args) => {
        if (lock.value) return
        lock.value = true
        try {
            const result = await fn(...args)
            closeLock()
            return result
        } catch (e) {
            closeLock()
            throw e
        }
    }

    _fn.lock = lock

    return _fn
}

export const lockFn = (fn, delay) => {
    let lock = false

    const closeLock = () => {
        if (typeof delay === 'number') {
            setTimeout(() => {
                lock = false
            }, delay)
        } else {
            lock = false
        }
    }

    return async (...args) => {
        if (lock) return
        lock = true
        try {
            const result = await fn(...args)
            closeLock()
            return result
        } catch (e) {
            closeLock()
            throw e
        }
    }
}